package com.ruoyi.mp.controller;

import com.alibaba.fastjson.JSONObject;
import com.egzosn.pay.common.util.sign.encrypt.MD5;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.EncryptAesUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.db.domain.system.MpClient;
import com.ruoyi.db.domain.system.MpClientOrder;
import com.ruoyi.mp.annotion.Login;
import com.ruoyi.mp.annotion.LoginUser;
import com.ruoyi.mp.service.IMpClientOrderService;
import com.ruoyi.mp.utils.KDNiaoUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 【用户订单】Controller
 * 
 * @author ruoyi
 * @date 2022-07-23
 */
@Api(value = "【用户订单】",tags ="【用户订单】")
@RestController
@RequestMapping("/smp/order")
public class MpClientOrderController extends BaseController
{
    private static Logger log = LoggerFactory.getLogger(MpClientOrderController.class);
    @Autowired
    private IMpClientOrderService mpClientOrderService;
    public final static String key = "T6hCxKDrG5E9DhIccGvJ6VXycJs09gb2";


    /**
     * 查询【用户订单】列表
     */
    @Login
    @ApiOperation(value = "查询【用户订单】列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="mpClientOrder",value="【用户订单】",paramType="query")
    })
    @GetMapping("/list")
    public TableDataInfo list(@LoginUser MpClient client, Long orderStatus)
    {
        try {
            startPage();
            MpClientOrder order = new MpClientOrder();
            order.setClientId(client.getClientId());
            order.setOrderStatus(orderStatus);
            List<MpClientOrder> list = mpClientOrderService.selectMpClientOrderListByStatus(order);
            return getDataTable(list);
        }catch (Exception e){
            log.error("【用户订单】发生异常",e);
        }
        return null;
    }
    /**
     * 查询【用户订单】详情
     */
    @Login
    @ApiOperation(value = "查询【用户订单】详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name="mpClientOrder",value="【用户订单详情】",paramType="query")
    })
    @GetMapping("/info")
    public AjaxResult info(String orderId)
    {
        try {
            return AjaxResult.success(mpClientOrderService.selectMpClientOrderByOrderId(orderId));
        }catch (Exception e){
            log.error("【商城用户】发生异常",e);
        }
        return AjaxResult.error("【商城用户】异常");
    }
    /**
     * 新增【用户订单】
     */
    @Login
    @ApiOperation(value = "新增【用户订单】/购买商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name="mpClientOrder",value="【用户订单】",dataType="MpClientOrder")
    })
    @Log(title = "【购买商品生成订单】", businessType = BusinessType.INSERT)
    @PostMapping("/pay")
    public AjaxResult add(@RequestBody MpClientOrder mpClientOrder,@LoginUser MpClient mpClient)
    {
//        String text= "procount"+mpClientOrder.getProCount()+"_"+"addressId"+mpClientOrder.getAddressId();
//        String encrySign= MD5.sign(text,key,"utf-8");
//        if(!encrySign.equals(sign)){
//            return AjaxResult.error("签名验证失败");
//        }
        if(mpClient.getIsVirtual()!=null&&mpClient.getIsVirtual()==1){
            return AjaxResult.success("虚拟号无法购买商品");
        }
        if(StringUtils.isBlank(mpClient.getPayPassword())){
            throw new ServiceException("请先设置交易密码");
        }
        String entryPwd = EncryptAesUtil.encrypt(mpClientOrder.getPayPassword());
        if(entryPwd==null||!mpClient.getPayPassword().equals(entryPwd)){
            throw new ServiceException("交易密码错误");
        }
        try {
            MpClientOrder mpClientOrderS =  mpClientOrderService.selectMpClientOrderByOrderId(mpClientOrder.getOrderId());
            mpClientOrderS.setSellType(mpClientOrder.getSellType());
            mpClientOrderService.insertMpClientOrder(mpClientOrderS,mpClient);
            return  AjaxResult.success();
        }catch (Exception e){
            log.error("新增【用户订单】发生异常",e);
        }
        return AjaxResult.error("【用户订单】异常");
    }

    /**
     * 提交订单
     */
    @Login
    @ApiOperation(value = "购买提交订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name="mpClientOrder",value="【用户订单】",dataType="MpClientOrder")
    })
    @Log(title = "【购买商品生成订单】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addOrder(@RequestBody MpClientOrder mpClientOrder,@LoginUser MpClient mpClient)
    {
//        String text= "procount"+mpClientOrder.getProCount()+"_"+"addressId"+mpClientOrder.getAddressId();
//        String encrySign= MD5.sign(text,key,"utf-8");
//        if(!encrySign.equals(sign)){
//            return AjaxResult.error("签名验证失败");
//        }
        try {
            if(mpClient.getIsVirtual()!=null&&mpClient.getIsVirtual()==1){
                return AjaxResult.success("虚拟号无法购买商品");
            }
            mpClientOrder.setClientId(mpClient.getClientId());
            mpClientOrder.setCreateTime(new Date());
            mpClientOrder.setOrderStatus(101l);
            MpClientOrder order = mpClientOrderService.insertMpClientOrderWaitPay(mpClientOrder);
            return  AjaxResult.success(order);
        }catch (Exception e){
            log.error("新增【用户订单】发生异常",e);
        }
        return AjaxResult.error("【用户订单】异常");
    }
    /**
     * 修改【用户订单】
     */
    @Login
    @ApiOperation(value = "修改【用户订单】")
    @ApiImplicitParams({
            @ApiImplicitParam(name="mpClientOrder",value="【用户订单】",dataType="MpClientOrder")
    })
    @Log(title = "【用户订单】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MpClientOrder mpClientOrder,@LoginUser MpClient client)
    {
        try {
            MpClientOrder order =  new MpClientOrder();
            order.setOrderStatus(mpClientOrder.getOrderStatus());
            order.setOrderId(mpClientOrder.getOrderId());
            mpClientOrderService.updateMpClientOrder(order);
            return AjaxResult.success("成功");
        }catch (Exception e){
            return AjaxResult.error("【用户订单】异常");
        }
    }
    /**
     * 获取订单物流详情
     */
    @Login
    @ApiOperation(value = "获取订单物流详情")
    @GetMapping("/getLogistics")
    public AjaxResult getLogistics(String orderId)
    {
        try {
            String res = mpClientOrderService.getOrderLogistInfo(orderId);
            JSONObject jsonObj = JSONObject.parseObject(res);
            return AjaxResult.success(jsonObj);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }


}
